<template>
  <view class="container">
    <!-- 新增商品按钮 -->
    <view class="action-bar">
      <button @click="showAddProductModal" class="action-button">新增商品</button>
    </view>

    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <input type="text" placeholder="请输入商品名称" class="search-input" v-model="SelectInfo"/>
      <button class="search-button" @click="select">搜索</button>
    </view>

	<!-- 商品列表 -->
	<scroll-view class="product-list" scroll-y="true" style="height: 300px; overflow: hidden;width: 95%;" @scroll="handleScroll">
	  <view v-if="productList.length === 0" style='display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%;'>
	    <image src='../../Resources/Image/空空如也.png' style='width: 120px; height:120px; margin-bottom: 10px;'></image>
	    <div><span style="font-size: 20px; font-weight: bold; color: #b3b3b3">暂未上架的商品</span></div>
	  </view>
	  <view class="product-item" v-for="(item, index) in productList" :key="index" @click="ChangeProduct(item)" style="cursor: pointer;">
	    <view class="product-info">
	      <text class="product-name">{{ item.goods_name }}</text>
	      <text class="product-price">进价：￥{{ item.goods_price_in }}</text>
	    </view>
	  </view>
	</scroll-view>

    <!-- 商品小计 -->
    <view class="subtotal-section">
      <view v-if="subtotalList.length === 0" style='display: flex;flex-direction: column;align-items: center;justify-items: center;'>
        <div><span style="font-size: 15px; font-weight: bold; color: #b3b3b3">点击商品名字选择商品</span></div>
      </view>
      <view class="subtotal-item" v-for="(subtotal, index) in subtotalList" :key="index">
        <text class="subtotal-name" @click="OutToProductList(subtotal)">{{ subtotal.goods_name }}</text>
        <view class="quantity-selector">
          <button class="quantity-button" @click="decreaseQuantity(index)">-</button>
          <text class="quantity-value">{{ subtotal.goods_count }}</text>
          <button class="quantity-button" @click="increaseQuantity(index)">+</button>
        </view>
        <text class="subtotal-price">小计:￥{{ subtotal.goods_sum_price}}</text>
      </view>
      <button class="action-button" @click="confirmSelection">确定</button>
    </view>
  </view>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import { config } from '../../config';
import { TokenStore } from '../../Store/TokenStore';
import { GoodsStore } from '../../Store/GoodsStore';
import { WareHouseStore } from '../../Store/WareHouseStore';

let productList = ref([]);

let AllProductList = ref([])

let SelectInfo = ref('');

const subtotalList = ref([]);

const WareHouse = ref({});

let subPrice = ref([]);

const showProductModal = ref(false);
const newProduct = ref({
  code: '',
  name: '',
  specification: '',
  costPrice: '',
  salePrice: '',
  status: '在售'
});

onMounted(() => {
	// GetWareHouse();
  AllGoods();
});

//-----------------------------------------懒加载逻辑---------------------------------------------------


const handleScroll = (event) => {
	console.log("调用滑动方法");
  // 微信小程序的事件对象中包含了scrollHeight, scrollTop, clientHeight
  console.log("事件返回"+event.detail)
  const { scrollHeight, scrollTop} = event.detail;
  const clientHeight = 300;
  console.log(scrollHeight,scrollTop,clientHeight)
  if (scrollTop + clientHeight >= scrollHeight) {
    console.log("---------------------------触发加载更多数据--------------")
    AllGoods();
  }
};

//----------------------------------------------------------------------------------------------------

//搜索逻辑
function select(){
	if(SelectInfo.value === ''){
		productList.value = AllProductLsit.value
		return ;
	}
	
	const searchedGoods = AllProductLsit.value.filter(item => item.goods_name === SelectInfo.value);
	console.log("查询出数据"+JSON.stringify(searchedGoods))
	productList.value = searchedGoods;
}

//获取所属仓库信息
// function GetWareHouse(){
// 	WareHouse.value = JSON.parse(WareHouseStore().warehouse)
// 	console.log("获取仓库信息"+WareHouse.value);
// 	WareHouseStore().renew();
	
// 	//向主界面返回状态信息
// 	WareHouseStore().setwarehouse(WareHouse.value.warehouse_name)
	
// 	if(WareHouse.value===''){
// 		uni.showToast({
// 		  title: "请返回主页面选择仓库",
// 		  icon: 'none'
// 		});
// 		return ;
// 	}
// }

//分页数据
let pageinfo = ref({
	size:5,
	page:1
})

//获取所有商品
function AllGoods() {
	
  uni.request({
    url: `${config.baseURL}/NGoods/AllGoods`,
    method: 'POST',
	data:pageinfo.value,
    header: {
      'content-type': 'application/json',
      'Authorization': TokenStore().token,
    },
    success: (res) => {
      if (res.data.data === 'error') {
        uni.showToast({
          title: "数据库错误",
          icon: 'error'
        });
      } else {
		  let data = JSON.parse(res.data.data);
		  let data2 = data.filter(item => item.goods_status === '上架');
		  productList.value.push(...data2)
		  AllProductList.value.push(...data2)
		  console.log("数据获取成功" + JSON.stringify(productList.value));
		  pageinfo.value.page+=pageinfo.value.size
      }
    },
    fail: (err) => {
      uni.showToast({
        title: err.errMsg,
        icon: 'error'
      });
    }
  });
}

function ChangeProduct(product) {
  const goodsIdExists = subtotalList.value.some(item => item.goods_id === product.id);

  if (!goodsIdExists) {
    let ProductPrice = {
      goods_id: product.id,
      goods_name: product.goods_name,
      goods_price_in: product.goods_price_in,
      goods_sum_price: product.goods_price_in,
      goods_count: 1
    };
    subtotalList.value.push(ProductPrice);
  } else {
    console.log('商品 ID 已存在，不允许插入');
    uni.showToast({
      title: "重复选择",
      icon: 'error'
    });
  }
}

function OutToProductList(subtotal) {
  console.log("传入要移除的商品" + JSON.stringify(subtotal));
  subtotalList.value = subtotalList.value.filter(item => item.goods_id !== subtotal.goods_id);
}

function increaseQuantity(index) {
  subtotalList.value[index].goods_count++;
  subtotalList.value[index].goods_sum_price = subtotalList.value[index].goods_count * subtotalList.value[index].goods_price_in;
}

function decreaseQuantity(index) {
  if (subtotalList.value[index].goods_count > 1) {
    subtotalList.value[index].goods_count--;
    subtotalList.value[index].goods_sum_price = subtotalList.value[index].goods_count * subtotalList.value[index].goods_price_in;
  }
}

function confirmSelection() {
	let data = JSON.stringify(subtotalList.value)
	console.log("放入pinia的数据"+data);
	GoodsStore().setgoods(data)
    console.log('商品已确认,已存入pinia');
	uni.navigateTo({
	  url:"/pages/OnBonds/OnBonds"
	 })
}

function cancelSelection() {
  console.log('选择已取消');
}

function showAddProductModal() {
  uni.showToast({
    title: "请前往商品管理",
    icon: 'error'
  });
}

function hideProductModal() {
  showProductModal.value = false;
}

function submitProduct() {
  console.log('提交商品', newProduct.value);
  hideProductModal();
}

function onProductStatusChange(e) {
  newProduct.value.status = e.target.value;
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #f0f4f8;
}

.action-bar {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  width: 80%;
  height: 40px;
  font-size: 15px;
  margin-bottom: 10px;
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.search-input {
  flex-grow: 1;
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #d4d6d9;
  margin-right: 10px;
}

.search-button {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  height: 30px;
  font-size: 14px;
}

.product-list {
  margin: 10px 0;
  background-color: #fff;
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-height: 300px; /* 固定高度 /
overflow-y: auto; / 可滑动 */
}

.product-item {
display: flex;
justify-content: space-between;
padding: 10px;
border-bottom: 1px solid #e5e7eb;
height: 40px;
}

.product-info {
display: flex;
align-items: center;
width: 100%;
}

.product-name {
font-size: 16px;
font-weight: 500;
color: #1d2129;
}

.product-price {
margin-left: auto;
font-size: 14px;
color: #6b7280;
}

.subtotal-section {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 10px;
padding: 20px;
background-color: #fff;
border-radius: 12px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
max-height: 300px; /* 固定高度 /
overflow-y: auto; / 可滑动 */
}

.subtotal-item {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
margin-bottom: 20px;
}

.subtotal-name {
font-size: 16px;
font-weight: 500;
color: #1d2129;
}

.quantity-selector {
display: flex;
align-items: center;
gap: 10px;
}

.quantity-button {
background-color: #e5e7eb;
border: none;
font-size: 9px;
cursor: pointer;
height: 25px;
width: 35px;
}

.quantity-value {
font-size: 14px;
}

.subtotal-price {
font-size: 14px;
color: #6b7280;
}

.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
}

.modal-content {
background-color: #fff;
padding: 20px;
border-radius: 8px;
width: 90%;
max-width: 500px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
font-size: 18px;
font-weight: bold;
color: #007aff;
border-bottom: 1px solid #eaeaea;
padding-bottom: 10px;
margin-bottom: 20px;
}

.modal-body {
margin: 20px 0;
}

.input-field-rounded, .textarea-field {
width: 95%;
padding: 10px;
margin-bottom: 20px;
border: 1px solid #eaeaea;
border-radius: 8px;
}

.picker {
padding: 10px;
background-color: #eaeaea;
border-radius: 8px;
margin-bottom: 20px;
}

.modal-footer {
display: flex;
justify-content: flex-end;
}

.modal-footer button {
margin-left: 10px;
}
</style>